<template>
  <view :class="theme">
    <view class="bg-3" style="z-index: 9; margin: 16rpx 0 130rpx;">
      <view v-for="(section, sectionIndex) in sections" :key="sectionIndex" class="m-30 bg-4 b-rounded-40 overflow-hidden"
        style="margin: 16rpx 32rpx">
        <view v-for="(option, optionIndex) in section" :key="option.key" @click="todo(option)"
          :hover-class="option.hideMore ? `none` : `op-[0.6]`" :style="{
            margin: `0 30rpx`,
            padding: `36rpx 0`,
            borderTopColor: $config.COLOR_3,
            borderTopStyle: `solid`,
            borderTopWidth: optionIndex ? `2rpx` : 0,
          }" class="flex-row items-center">
          <text class="flex-1 ml-30 mr-30 text-28">{{ option.title }}</text>
          <text v-if="option.description" class="color-9 text-28 mr-12">
            {{ option.description }}
          </text>
          <uv-icon v-if="!option.hideMore" size="28" name="arrow-right" color="#999" />
        </view>
      </view>

      <button v-if="userInfo[$config.FIELD_TOKEN]" @click="logout" hover-class="op-[0.6]"
        class="items-center justify-center bg-5 lh-[3] color-15 text-28 fw-700 b-rounded-50" style="margin: 88rpx 30rpx">
        退出登录
      </button>

      <view @click="debug" class="h-60 items-center justify-center">
        <text v-if="$config.DEBUG_MODE" class="color-8">Click {{ limit }} times consecutively to exit DEBUG mode.</text>
      </view>
    </view>

    <!-- <text class="fixed bottom-88 left-50% color-9 h-36" style="transform: translateX(-50%);">蜀ICP备2023021293号-3A</text> -->

    <uv-popup :ref="(e: any) => (showPopup.warn = e)" mode="center" :close-on-click-overlay="false"
      :overlay-style="{ backdropFilter: `blur(10rpx)` }">
      <view class="w-620" style="padding: 120rpx 0;">
        <view class="bg-4 p-40 b-rounded-20">
          <uv-image width="166" height="166" src="/static/img/icon-warn.png" mode="widthFix"
            class="absolute top-62 left-224" />
          <text class="mt-90 text-36 color-5 fw-600" style="text-align: center">注销警告</text>
          <text
            class="mt-20 text-26 lh-loose color-2">账号内所有数据(包含个人信息、订单、余额、订阅服务等)将被清空,您可阅读《注销服务条款》了解详细信息。如果你同意，请点击确认按钮以注销账号。</text>
          <view class="m-30 b-rounded-20 overflow-hidden text-28">
            <input v-for="(item, key) in formData" :key="key" v-model="item.value" :type="item.type"
              class="mb-24 bg-3 b-rounded-30 p-18 text-28" :maxlength="item.maxlength" :placeholder="item.placeholder"
              placeholder-class="text-24 color-9" />
          </view>
          <view class="flex-row justify-evenly flex-1">
            <button @click="changePopup(false, 'warn')" hover-class="op-[0.6]"
              class="flex-1 bg-0 color-5 text-36 b-rounded-30 mr-30 lh-loose text-32"
              :style="{ border: `2rpx solid ${$config.COLOR_5}` }" plain>
              取消
            </button>
            <button @click="signOut" hover-class="op-[0.6]"
              class="flex-1 bg-0 color-15 text-36 b-rounded-30 bg-5 lh-loose text-32 fw-600 !border-none"
              :style="{ border: `none` }" plain>
              确认
            </button>
          </view>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script lang="ts" setup>
import { checkVersion } from "@/common/libs/dependency";
import { useMapState } from "@/common/libs/store";
import { formatPhoneNumber, getClient, transformURL } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";
import { ref, computed, reactive } from "vue";

const { theme } = useMapState(["theme"]);
const { $config = {} } = getApp().globalData || {};
const formData = reactive<AnyObject>({
  signOutText: {
    value: "",
    placeholder: `输入【我已确认】以确认注销`,
    errorMessage: `请输入【我已确认】以确认注销`,
    maxlength: 4,
    rule: /^我已确认$/,
    type: "text"
  },
  password: {
    value: "",
    placeholder: "输入安全密码以确保本人操作",
    errorMessage: "安全密码输入有误",
    maxlength: 6,
    rule: /^[0-9]{6}$/,
    type: "password"
  },
});

const showPopup = reactive({
  warn: {} as AnyObject,
});

const buildDocumentURL = (title: string, api: string) =>
  transformURL("/pages/common/webview", {
    title,
    url: encodeURIComponent(
      transformURL(
        "/html/document.html",
        { title },
        $config.URL_REMOTE + $config.API_PREFIX + api
      )
    ),
  });

const changePopup = (e: boolean, popupKey: keyof typeof showPopup) => {
  showPopup[popupKey][e ? "open" : "close"]();
};

const sections = computed<
  Array<
    {
      key: string;
      title: string;
      description?: string;
      hideMore?: boolean;
      url?: string;
    }[]
  >
>(() => [
  [
    {
      key: "loginPassword",
      title: "登录密码",
      description: "******",
      url: "/pages/client/auth/reset",
    },
    {
      key: "payPassword",
      title: "支付密码",
      description: "点击设置",
      url: "/pages/client/auth/setPayPassword",
    },
    {
      key: "payPassword",
      title: "手机号码",
      description: formatPhoneNumber(userInfo.value.mobile) || "-",
      hideMore: true,
    },
  ],
  [
    { key: "userAgreement", title: "用户协议" },
    { key: "privacyPolicy", title: "隐私政策" },
    // #ifndef MP
    { key: "signOut", title: "注销账号" },
    // #endif
    {
      key: "download",
      title: "分享APP",
      url: "/pages/common/download",
    },
    {
      key: "versionUpdate",
      title: "版本更新",
      hideMore: [1, 2, 3, 4].includes(getClient()),
      description: `Version ${$config.APP_VERSION}`,
    },
  ],
]);

const userInfo = ref<any>({});

onLoad(() => {
  uni.getStorage({
    key: $config.STORAGE_KEY_USER_INFO,
    success(data) {
      userInfo.value = data;
    },
  });
});

const logout = async () => {
  uni.showModal({
    title: "温馨提示",
    content: "确认退出吗",
    success({ cancel }) {
      if (cancel) return;
      uni.removeStorage({ key: $config.STORAGE_KEY_USER_INFO });
      uni.reLaunch({ url: $config.PAGE_LOGIN_ACCOUNT });
    }
  });
};

const signOut = async () => {
  for (const key in formData) {
    const item = formData[key];
    if (!item.rule.test(item.value)) {
      return uni.showToast({ title: item.errorMessage, icon: "none" });
    }
  }
  changePopup(false, "warn");
  uni.request({
    url: "/cancelUser",
    data: { password: formData.password.value },
    success() {
      uni.clearStorage();
      uni.reLaunch({ url: "/pages/index" });
    }
  });
};

const todo = (option: typeof sections.value[number][number]) => {
  if (option.hideMore) return;
  switch (option.key) {
    case "userAgreement":
    case "privacyPolicy":
      const map = {
        privacyPolicy: {
          api: "/privateInfo",
          title: "隐私政策",
        },
        userAgreement: {
          api: "/userAgreementInfo",
          title: "服务协议",
        },
      },
        { api, title } = map[option.key as keyof typeof map];
      uni.navigateTo({ url: buildDocumentURL(title, api) });
      break;
    case "signOut":
      changePopup(true, "warn");
      break;
    case "versionUpdate":
      [5, 6, 9, 10].includes(getClient()) && checkVersion({ showToast: true });
      break;
    default:
      uni.navigateTo({ url: option.url! });
      break;
  }
};

let [duration, lastTime, count, limit] = [200, Date.now(), 0, 5];
const debug = () => {
  const currentTime = Date.now();
  count = (currentTime - lastTime) < duration ? count + 1 : 1;
  lastTime = currentTime;
  if (count !== limit) return;
  const timer = setTimeout(() => {
    clearTimeout(timer);
    uni.setStorageSync("$debug", { DEBUG_MODE: !$config.DEBUG_MODE });
    // #ifdef APP-PLUS
    plus.runtime.restart();
    // #endif

    // #ifdef H5
    location.reload();
    // #endif

    // #ifdef MP
    uni.showToast({ title: "Restart the mini program to enter debugging mode.", icon: "none" });
    // #endif
  }, duration + 10);
}

</script>

<style lang="scss" scoped>
// scss
</style>
